package ctm.javacode;

import java.io.* ;
import java.util.*;
import java.sql.*;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/register.do")

public class register extends HttpServlet {

	private final String SUCCESS_VIEW = "main.jsp";  
	private final String ERROR_VIEW = "registerError.jsp"; 
	
	protected void doPost(HttpServletRequest request,
								HttpServletResponse response )
								throws ServletException, IOException {
		String nextpage = ERROR_VIEW;
		
		String ac = request.getParameter("newaccount") ;
		String pw = request.getParameter("newpw") ;
		String repw = request.getParameter("renewpw") ;
		String mail = request.getParameter("email") ;
		String role = request.getParameter("role");
		
		List<String> errors = new ArrayList<String>() ;
		
		try {
			if (isInvalidAccount( ac ))
				errors.add("帳號不符合規定或者帳號已經存在");
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		if (isInvalidPW( pw ))
			errors.add("密碼格式不正確");
		if ( ! pw.equals(repw))
			errors.add("密碼不一致");
		if (isInvalidMail( mail ))
			errors.add("E-mail格式不正確,請您注意必須使用小寫");
		
	
		
		if ( errors.isEmpty() ) {
			nextpage = SUCCESS_VIEW ;
			try {
				creatUserData(ac, pw, mail, role);
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} // end if
		else {
			request.setAttribute("errors", errors) ;
		} // end else
			
	
		request.getRequestDispatcher(nextpage)
		   .forward(request, response);
	} // end doPost()

	private void creatUserData(String ac, String pw, String mail, String role ) throws NamingException, SQLException {
		DbBean creatData = new DbBean("jdbc/ctmpllab");
		pw = MD5encrypt.generate(pw);//用md5加密帳戶密碼
		
		String sqlQuery = "INSERT INTO ACCOUNTABLE(account, password, role, mail) VALUES('"
					+ ac + "', '" + pw + "', '" + role + "', '" + mail + "')" ;	
		

		if (creatData.isConnectedOK()) {
			try {
				creatData.ExcuteUpdate(sqlQuery);		    
			} catch(SQLException e) {
				throw new SQLException(e) ;
			} // end try-catch				
		} // end if
		else {
			System.out.println( "DataBase連接錯誤" );
		} // end else 				
			
	}

	private boolean isInvalidMail(String mail) {
		return mail == null || ! mail.matches("^[_a-z0-9]+([.]" + "[_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$");
		
	}

	private boolean isInvalidPW(String pw) {
		return pw== null || pw.length() < 6 || pw.length() > 12 ;
	
	}

	private boolean isInvalidAccount(String ac) throws NamingException, SQLException {
		DbBean db = new DbBean("jdbc/ctmpllab");
		ResultSet rs ;
		
		if (db.isConnectedOK()) {
			try {
				rs = db.ExcuteResult("SELECT * FROM ACCOUNTABLE");		    
			} catch(SQLException e) {
				throw new SQLException(e) ;
			} // end try-catch
			
			while (rs.next()) {
				if ( rs.getString("account").trim().equals(ac) )
					return true;
			} // end while
			
			if ( ac.length() < 6 || ac.length() > 12 )
				return true;
		} // end if
		else {
			System.out.println( "DataBase連接錯誤" );
		} // end else 
			
		return false ;
	}
	
} // end class register

